package com.zhkj.txg.module.cart.popup

import android.content.Context
import android.view.Gravity
import android.view.View
import android.widget.EditText
import com.zhkj.txg.R
import com.zhkj.txg.utils.TextWatcherWrapper
import razerdp.basepopup.BasePopupWindow
import razerdp.util.KeyboardUtils
import java.math.BigDecimal

class CartNumberChangePopupWindow(
    context: Context,
    private val onConfirm: (uiPosition: Int, currentCount: Int) -> Unit
) : BasePopupWindow(context) {

    init {
        setOutSideDismiss(false)
        popupGravity = Gravity.CENTER
        setAutoShowInputMethod(true)
    }

    // 原始的数量
    private var originCount: Int = 1

    // 当前的列表index
    private var uiPosition: Int = -1

    // 库存
    private var maxStock: Int = 1

    private lateinit var etNumber: EditText

    override fun onCreateContentView(): View = createPopupById(R.layout.popup_change_number)
    override fun onViewCreated(contentView: View?) {
        contentView?.let { view ->
            etNumber = view.findViewById(R.id.etChangeNumber)
            etNumber.setText(originCount.toString())
            etNumber.addTextChangedListener(TextWatcherWrapper {
                if (!it.isNullOrEmpty()) {
                    if (it.startsWith("0")) {
                        // 为空或0，则设置为1
                        etNumber.setText("1")
                        etNumber.setSelection(1)
                    } else if (BigDecimal(it.toString()) > BigDecimal(maxStock)) {
                        // 比库存量大，则设置为库存值
                        etNumber.setText(maxStock.toString())
                        etNumber.setSelection(maxStock.toString().length)
                    }
                }
            })
            view.findViewById<View>(R.id.tvCancel).setOnClickListener { dismiss() }
            view.findViewById<View>(R.id.tvConfirm).setOnClickListener {
                onConfirm(uiPosition, if (etNumber.text.isNullOrEmpty()) 1 else etNumber.text.toString().toInt())
                dismiss()
                if (KeyboardUtils.isOpen()) KeyboardUtils.close(etNumber)
            }
        }
    }

    fun setData(originCount: Int, stock: Int, uiPosition: Int) {
        this.originCount = originCount
        this.uiPosition = uiPosition
        maxStock = stock
        findViewById<EditText>(R.id.etChangeNumber)?.let {
            it.setText(originCount.toString())
            it.setSelection(originCount.toString().length)
        }
    }
}